const http = require('http')
const server = http.createServer()
const fs = require('fs')
const path = require('path')
const qs = require('querystring')

server.on('request', (req, res) => {
    if (req.url === '/api/province') {
        fs.readFile(path.join(__dirname, 'city.json'), (err, data) => {
            if (err) return console.log(err)
            const obj = JSON.parse(data.toString())
            res.setHeader('Content-Type', 'text/html;charset=utf-8')
            res.end(JSON.stringify(obj.map(item => item.provinceName)))
        })
    } else if (req.url.startsWith('/api/city')) {
        const paramStr = req.url.split('?')[1]
        const paramObj = qs.parse(paramStr)
        fs.readFile(path.join(__dirname, 'city.json'), (err, data) => {
            if (err) return console.log(err)
            const obj = JSON.parse(data.toString())
            const newobj = obj.find(item => item.provinceName === paramObj.pname)
            res.setHeader('Content-Type', 'text/html;charset=utf-8')
            let arr = []
            newobj.cities.forEach(item => {
                if (item.cityName !== '省直辖行政单位') {
                    arr.push(item.cityName)
                }
                else {
                    let zxs = item.counties.map(item => item.countyName)
                    arr = arr.concat(zxs)
                }
            })
            res.end(JSON.stringify(arr))
        })
    } else if (req.url.startsWith('/api/area')) {
        const paramStr = req.url.split('?')[1]
        const paramObj = qs.parse(paramStr)
        fs.readFile(path.join(__dirname, 'city.json'), (err, data) => {
            if (err) return console.log(err)
            const obj = JSON.parse(data.toString())
            let newobj = obj.find(item => item.provinceName === paramObj.pname)
            res.setHeader('Content-Type', 'text/html;charset=utf-8')

            newobj = newobj.cities.find(item => item.cityName === paramObj.cname)
            // console.log(newobj)
            const areaList = newobj.counties.map(item => item.countyName)
            // console.log(areaList)
            // res.end(JSON.stringify(newobj))
            const newlist = areaList.filter(item => item !== '市辖区')
            res.end(JSON.stringify(newlist))
        })
    } else {
        res.setHeader('Content-Type', 'text/html;charset=utf-8')
        res.end('您请求的资源不存在')
    }
})
server.listen(3000, () => {
    console.log('服务启动了')
})